<template>
  <div class="property-container">
    <h2 class="page-title">物业缴费</h2>

    <el-card class="payment-card">
      <!-- 年份选择器 -->
      <div class="year-selector">
        <el-form :inline="true">
          <el-form-item label="查询年份">
            <el-date-picker
              v-model="yearRange.start"
              type="year"
              placeholder="开始年份"
              value-format="YYYY"
            />
            <span class="separator">至</span>
            <el-date-picker
              v-model="yearRange.end"
              type="year"
              placeholder="结束年份"
              value-format="YYYY"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 账单分类选项卡 -->
      <el-tabs v-model="activeTab">
        <el-tab-pane label="待支付" name="unpaid">
          <el-table 
            :data="filteredBills"
            style="width: 100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="账单周期" width="180">
              <template #default="{row}">
                {{ row.periodStart }} 至 {{ row.periodEnd }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{row}">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="缴费状态" width="120">
              <template #default="{row}">
                <el-tag 
                  :type="getStatusType(row)" 
                  effect="plain"
                >
                  {{ statusText(row.status) }}
                  <span v-if="isUrgent(row)">（即将到期）</span>
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="dueDate" label="截止日期" width="150">
              <template #default="{row}">
                {{ formatDate(row.dueDate) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handleSinglePay(row)"
                  :disabled="row.status !== '未支付'"
                >
                  立即支付
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="已支付" name="paid">
          <el-table :data="paidBills" style="width: 100%" v-loading="loading">
            <el-table-column label="账单周期" width="180">
              <template #default="{row}">
                {{ row.periodStart }} 至 {{ row.periodEnd }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="{row}">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column label="缴费状态" width="120">
              <template #default="{row}">
                <el-tag type="success" effect="plain">{{ statusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="paidAt" label="支付时间" width="150">
              <template #default="{row}">
                {{ formatDate(row.paidAt) }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 底部操作栏 -->
      <div class="action-bar" v-if="activeTab === 'unpaid' && selectedBills.length">
        已选 {{ selectedBills.length }} 项，合计：
        <span class="total-amount">
          ¥{{ totalSelectedAmount.toFixed(2) }}
        </span>
        <el-button 
          type="primary" 
          @click="handleBatchPay"
        >
          合并支付
        </el-button>
      </div>
    </el-card>
    
    <!-- 支付对话框 -->
    <el-dialog
      v-model="showPaymentDialog"
      :title="paymentDialogTitle"
      width="400px"
    >
      <div class="payment-dialog-content">
        <div class="payment-amount">
          <span class="label">支付金额：</span>
          <span class="amount">¥{{ currentPaymentAmount.toFixed(2) }}</span>
        </div>
        <div class="payment-method">
          <h4>选择支付方式</h4>
          <el-radio-group v-model="selectedPaymentMethod">
            <el-radio label="微信">微信支付</el-radio>
            <el-radio label="支付宝">支付宝</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPaymentDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="paying">确认支付</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { selectResidentPropertyFees, createPayment1 } from '@/api/api'

const loading = ref(false)
const bills = ref([])
const activeTab = ref('unpaid')
const selectedBills = ref([])
const showPaymentDialog = ref(false)
const selectedPaymentMethod = ref('支付宝')
const currentBill = ref(null)
const paying = ref(false)
const yearRange = ref({
  start: new Date().getFullYear(),
  end: new Date().getFullYear() + 1
})

// 计算属性
const filteredBills = computed(() => {
  return bills.value.filter(bill => bill.status === '未支付')
})

const paidBills = computed(() => {
  return bills.value.filter(bill => bill.status === '已支付')
})

const totalSelectedAmount = computed(() => {
  return selectedBills.value.reduce((sum, bill) => sum + bill.amount, 0)
})

const currentPaymentAmount = computed(() => {
  if (selectedBills.value.length > 0) {
    return totalSelectedAmount.value
  }
  return currentBill.value?.amount || 0
})

const paymentDialogTitle = computed(() => {
  return selectedBills.value.length > 1 ? '合并支付' : '支付账单'
})

// 方法定义提前
const fetchPropertyFees = async () => {
  if (!yearRange.value.start || !yearRange.value.end) {
    return
  }

  loading.value = true
  try {
    const userId = JSON.parse(localStorage.getItem('userInfo'))?.userId
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }
    
    const res = await selectResidentPropertyFees(
      parseInt(yearRange.value.start), 
      parseInt(yearRange.value.end)
    )
    
    if (res.code === 200 && res.data) {
      bills.value = res.data
    } else {
      ElMessage.error('获取物业费记录失败')
    }
  } catch (error) {
    console.error('获取物业费失败:', error)
    ElMessage.error('获取物业费失败')
  } finally {
    loading.value = false
  }
}

// 监听年份变化并自动调整和查询
watch(() => yearRange.value.start, (newStart) => {
  if (newStart) {
    yearRange.value.end = String(parseInt(newStart) + 1)
    fetchPropertyFees()
  }
}, { immediate: true }) // immediate: true 确保初次加载时也会触发

watch(() => yearRange.value.end, (newEnd) => {
  if (newEnd) {
    yearRange.value.start = String(parseInt(newEnd) - 1)
    fetchPropertyFees()
  }
})

// 其他方法
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '--'
}

const statusText = (status) => {
  return status === '已支付' ? '已支付' : '待支付'
}

const getStatusType = (bill) => {
  if (bill.status === '已支付') return 'success'
  return isUrgent(bill) ? 'danger' : 'warning'
}

const isUrgent = (bill) => {
  const dueDate = dayjs(bill.dueDate)
  const today = dayjs()
  return bill.status === '未支付' && dueDate.diff(today, 'day') <= 3
}

const handleSelectionChange = (selection) => {
  selectedBills.value = selection
}

const handleSinglePay = (bill) => {
  currentBill.value = bill
  selectedBills.value = [bill]
  showPaymentDialog.value = true
}

const handleBatchPay = () => {
  if (selectedBills.value.length === 0) {
    ElMessage.warning('请选择要支付的账单')
    return
  }
  showPaymentDialog.value = true
}

const confirmPayment = async () => {
  if (!selectedPaymentMethod.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  paying.value = true
  try {
    for (const bill of selectedBills.value) {
      const res = await createPayment1(bill.feeId, bill.amount)
      if (res.code === 200) {
        bill.status = '已支付'
        bill.paidAt = new Date().toISOString()
      } else {
        ElMessage.error(`账单 ${bill.feeId} 支付失败`)
        return
      }
    }
    ElMessage.success('支付成功')
    showPaymentDialog.value = false
    selectedBills.value = []
    currentBill.value = null
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  } finally {
    paying.value = false
  }
}

onMounted(() => {
  // 初次加载时已由 watch 处理，无需再次调用
})
</script>

<style scoped>
.property-container {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
}

.payment-card {
  margin-bottom: 20px;
}

.action-bar {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 20px;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.payment-dialog-content {
  padding: 20px 0;
}

.payment-amount {
  text-align: center;
  margin-bottom: 30px;
}

.payment-amount .label {
  font-size: 16px;
}

.payment-amount .amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.payment-method {
  padding: 0 20px;
}

.payment-method h4 {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.year-selector {
  margin-bottom: 20px;
}

.separator {
  margin: 0 10px;
  color: #606266;
}

.el-date-picker {
  width: 140px;
}
</style>